import numpy as np
import csv


def load_data(file_path):
    """
    Load city district statistics
    Columns: district, population, avg_rent, area_km2
    Return: 2D array of shape (districts, 3) containing [population, avg_rent, area_km2]
    """
    data = []
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            reader = csv.reader(file)
            next(reader)  # 跳过标题行
            for row in reader:
                # 提取人口、平均租金和面积数据
                data.append([int(row[1]), int(row[2]), float(row[3])])
    except FileNotFoundError:
        print(f"错误: 文件 {file_path} 未找到。")
    except Exception as e:
        print(f"错误: 发生了一个未知错误: {e}")
    return np.array(data)


def calculate_statistics(data):
    """
    Calculate city metrics statistics
    Return: Dictionary containing mean, median, variance, std for each metric
    """
    means = np.mean(data, axis=0)
    medians = np.median(data, axis=0)
    variances = np.var(data, axis=0)
    stds = np.std(data, axis=0)
    return {
        'means': means,
        'medians': medians,
        'variances': variances,
        'stds': stds
    }


def print_results(stats):
    """
    Print formatted results with 4-space indentation
    """
    metrics = ['Population', 'Average Rent', 'Area (km²)']
    for metric, mean, med, var, std in zip(metrics,
                                          stats['means'],
                                          stats['medians'],
                                          stats['variances'],
                                          stats['stds']):
        print(f"{metric}:")
        print(f"    Average: {mean:.1f}")
        print(f"    Median: {med:.1f}")
        print(f"    Variance: {var:.1f}")
        print(f"    Standard Deviation: {std:.1f}")

# Execution flow
city_data = load_data('shanghai.csv')
stats = calculate_statistics(city_data)
print_results(stats)
